<?php

namespace app\home\logic;

use alisms\Sms;
use app\common\logic\Base;
use think\facade\App;
use think\facade\Env;
use app\common\logic\Email;
use think\facade\Log;

class User extends  Base {

    /**
     * @desc 登录操作
     * @param $params
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginAjax($params) {
        if($params['username'] && $params['password']) {
            $where = [
                'user_phone' => $params['username'],
                'user_email' => $params['username'],
            ];
          
            $userInfo = model('User', 'Logic')->whereOr($where)->find();
 
            if(!$userInfo) {
                $this->errorCode = EC_HOME_USERNAME_NOT_EXIST;
                return false;
            }
            $md5Password = App::model('User')->generatePassword($params['password'], $userInfo['user_salt']);
            if(strcmp($md5Password, $userInfo['user_password']) != 0) {
                $this->errorCode = EC_HOME_USERNAME_PASSWORD_ERROR;
                return false;
            }
        }else if($params['phone'] && $params['phoneCode']){
            $userInfo = App::model('User')->where(['user_phone' => $params['phone']])->find();
            if(!$userInfo) {
                $this->errorCode = EC_HOME_USER_PHONE_NOT_EXIST;
                return false;
            }

            if(!check_msg_code($params['tag']. $params['phone'], $params['phoneCode'])) {
                $this->errorCode = EC_HOME_PHONE_CODE_ERROR;
                return false;
            }
        }else {
            $this->errorCode = EC_PARAMS_ILLEGAL;
            return false;
        }

        session('userId', $userInfo['user_id']);
        return [
            'url' => url('url/index')
        ];
    }
    
    /**
     * @desc 注册操作
     * @param array $params
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function registerAjax($params) {
        $userName  = App::model('User')->setUserName();
        $secretID  = App::model('User')->generateSecretID();
        $secretKey = App::model('User')->generateSecretKey();
        
        if($params['phone'] && $params['phoneCode'] && $params['password1']) {
            $userInfo = App::model('User')->where(['user_phone' => $params['phone']])->find();
            if($userInfo) {
                $this->errorCode = EC_HOME_USER_PHONE_ALREADY_EXIST;
                return false;
            }
    
            //验证手机注册码
            if(!check_msg_code($params['tag'].$params['phone'], $params['phoneCode'])) {
                $this->errorCode = EC_HOME_PHONE_CODE_ERROR;
                return false;
            }
    
            $data = [
                'user_name'        => $userName,
                'user_phone'       => $params['phone'],
                'user_salt'        => random_string(8),
                'user_secret_id'   => $secretID,
                'user_secret_key'  => $secretKey,
                'user_create_time' => date('Y-m-d H:i:s')
            ];
            $data['user_password'] = App::model('User')->generatePassword($params['password1'], $data['user_salt']);
            
        } else if($params['email'] && $params['emailCode'] && $params['password2']) {
            $userInfo = App::model('User')->where(['user_email' => $params['email']])->find();
            if($userInfo) {
                $this->errorCode = EC_HOME_USER_EMAIL_ALREADY_EXIST;
                return false;
            }
    
            //验证邮件注册码
            if(!check_msg_code($params['tag'].$params['email'], $params['emailCode'])) {
                $this->errorCode = EC_HOME_EMAIL_CODE_ERROR;
                return false;
            }
    
            $data = [
                'user_name'        => $userName,
                'user_email'       => $params['email'],
                'user_salt'        => random_string(8),
                'user_secret_id'   => $secretID,
                'user_secret_key'  => $secretKey,
                'user_create_time' => date('Y-m-d H:i:s')
            ];
            $data['user_password'] = App::model('User')->generatePassword($params['password2'], $data['user_salt']);
        }else {
            $this->errorCode = EC_PARAMS_ILLEGAL;
            return false;
        }
        
        $userId = App::model('User')->insertGetId($data);
        if($userId === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
    
    /**
     * @desc 通过手机号找回密码
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function findPasswordByPhoneAjax($params) {
        $userInfo = App::model('User')->where(['user_phone' => $params['phone']])->find();
        if(!$userInfo) {
            $this->errorCode = EC_HOME_USER_PHONE_NOT_EXIST;
            return false;
        }
        
        //验证手机注册码
        if(!check_msg_code('findPassword'. $params['phone'], $params['phoneCode'])) {
            $this->errorCode = EC_HOME_PHONE_CODE_ERROR;
            return false;
        }

        $md5Password = App::model('User')->generatePassword($params['password'], $userInfo['user_salt']);
        
        $result = App::model('User')->where(['user_id' => $userInfo['user_id']])->update(['user_password' => $md5Password]);
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
    
    /**
     * @desc 通过邮箱找回密码
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function findPasswordByEmailAjax($params) {
        $userInfo = App::model('User')->where(['user_email' => $params['email']])->find();
        if(!$userInfo) {
            $this->errorCode = EC_HOME_USER_EMAIL_NOT_EXIST;
            return false;
        }
    
        //验证手机注册码
        if(!check_msg_code('findPassword'. $params['email'], $params['emailCode'])) {
            $this->errorCode = EC_HOME_EMAIL_CODE_ERROR;
            return false;
        }
    
        $md5Password = App::model('User')->generatePassword($params['password'], $userInfo['user_salt']);
    
        $result = App::model('User')->where(['user_id' => $userInfo['user_id']])->update(['user_password' => $md5Password]);
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
    
    /**
     * @dsec 获取注册验证码
     * @param $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPhoneCode($params) {
        if(!$params['phone']){
            $this->errorCode = EC_HOME_PHONE_VERIFICATION_CODE_SEND_FAIL;
            return false;
        }
        $userInfo = model('User')->where(['user_phone' => $params['phone']])->find();
        switch ($params['tag']) {
            case 'login': {
                if(!$userInfo) {
                    $this->errorCode = EC_HOME_USER_PHONE_NOT_EXIST; //手机号不存在
                    return false;
                }
                break;
            }
            case 'register': {
                if($userInfo) {
                    $this->errorCode = EC_HOME_USER_PHONE_ALREADY_EXIST; //手机号已存在
                    return false;
                }
                break;
            }
            case 'findPassword': {
                if(!$userInfo) {
                    $this->errorCode = EC_HOME_USER_PHONE_NOT_EXIST; //手机号不存在
                    return false;
                }
                break;
            }
            default:{
                return true;
            }
        }
    
        $code = create_msg_code($params['tag']. $params['phone']);
        
        //生产环境才发送短信
        if(Env::get('app.environment') == 'production'){
            Sms::sendSms($params['phone'], $code);
        }

        return true;
    }
    
    /**
     * @dsec 通过邮件获取验证码
     * @param $params
     * @return bool
     * @throws \PHPMailer\PHPMailer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getEmailCode($params) {
        if(!$params['email']){
            $this->errorCode = EC_HOME_EMAIL_VERIFICATION_CODE_SEND_FAIL;
            return false;
        }
        
        $userInfo = model('User')->where(['user_email' => $params['email']])->find();
        
        switch ($params['tag']) {
            case 'login': {
                if(!$userInfo) {
                    $this->errorCode = EC_HOME_USER_EMAIL_NOT_EXIST;
                    return false;
                }
                break;
            }
            case 'register': {
                if($userInfo) {
                    $this->errorCode = EC_HOME_USER_EMAIL_ALREADY_EXIST;
                    return false;
                }
                break;
            }
            case 'findPassword': {
                if(!$userInfo) {
                    $this->errorCode = EC_HOME_USER_EMAIL_NOT_EXIST;
                    return false;
                }
                break;
            }
            default:{
                return true;
            }
        }
    
        $code = create_msg_code($params['tag'] . $params['email']);
        $Email = new Email();
        $result = $Email->sendMail($params['email'], '邮箱注册验证码', '您的邮箱验证码是'. $code.'。5分钟内有效。请勿泄露！');
        if($result === false) {
            Log::write($Email->message, 'info', true);
            $this->errorCode = EC_HOME_EMAIL_VERIFICATION_CODE_SEND_FAIL;
            return false;
        }
        return true;
    }
}
